const express = require('express')
const { getAll, getOne, exec } = require('../db')
//创建router路由对象
const router = express.Router()

router.get('/', async (req, res) => {
  const { page = 1, size = 5 } = req.query
  let sql = `select  count(*) as total  from blog_category`
  let { total } = await getOne(sql)
  let offset = (page - 1) * size
  sql = `select id,type from blog_category limit ${offset}, ${size}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询分类成功',
    result: { total, data },
  })
})

//获取所有
//分页Get/users?page=1&size=5
router.get('/search', async (req, res) => {
  const { page = 1, size = 5, keywords } = req.query
  //as abc 给count（*）起别名，count（*）是字段总数
  let sql = `select count(*) as total from blog_category where type like '%${keywords}%' `
  let { total } = await getOne(sql)
  //偏移量=（page-1)*size
  let offset = (page - 1) * size
  sql = `select id,type from blog_category  where  type like '%${keywords}%' limit ${offset}, ${size};`
  console.log(sql)
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: { total, data },
  })
})

router.get('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `select * from blog_category where id = ${id} `
  const data = await getOne(sql)
  console.log(data)
  res.send({
    code: 0,
    message: '查询分类成功',
    result: data,
  })
})

router.post('/', async (req, res) => {
  console.log(req.body)
  const { type } = req.body
  let sql = `insert into blog_category (type) values ('${type}')`
  const { insertId } = await exec(sql)
  res.send({
    code: 0,
    message: '添加文章分类成功',
    result: {
      id: insertId,
      type,
    },
  })
})

router.put('/:id', async (req, res) => {
  const { id } = req.params
  const { type } = req.body

  let sql = `update blog_category set  type='${type}' where id=${id}`
  await exec(sql)

  res.send({
    code: 0,
    message: '修改分类成功',
    result: {
      id,
      type,
    },
  })
})

module.exports = router
